package com.example.springboot4.system.config;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.example.springboot4.system.constant.FieldConstants;
import com.example.springboot4.system.model.LoginUser;
import com.example.springboot4.system.util.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 处理新增和更新的基础数据填充，配合BaseEntity和MyBatisPlusConfig使用
 *
 * @author 宋义州
 * @since 2022-08-09  23:06
 */
@Component
public class MybatisMetaHandler implements MetaObjectHandler {

    /**
     * 新增时的填充策略
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (BeanUtil.isNotEmpty(loginUser)) {
            //设置创建时间
            this.setFieldValByName(FieldConstants.CREATE_TIME, LocalDateTime.now(), metaObject);
            //设置创建人id
            this.setFieldValByName(FieldConstants.CREATE_USER, loginUser.getUserId(), metaObject);
        }
    }

    /**
     * 更新时的填充策略
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (BeanUtil.isNotEmpty(loginUser)) {
            //设置更新时间
            this.setFieldValByName(FieldConstants.UPDATE_TIME, LocalDateTime.now(), metaObject);
            //设置更新人id
            this.setFieldValByName(FieldConstants.UPDATE_USER, loginUser.getUserId(), metaObject);
        }
    }
}
